<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item :span="24">
          <!--插入seach组件-->
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts"
                  @blur="getTenantInfoListHttp"></Search>
        </el-form-item>
        <el-form-item>
          <el-button  @click="createTenant" :disabled="butStatus.add" type="success">创建</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="updateTenant" :disabled="butStatus.modify">修改</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="gotopage42" :disabled="butStatus.deploy">配置资源</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="deleteTenant" :disabled="butStatus.rm" type="danger">删除</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <template>
      <el-table v-loading="listLoading" :data="tableData" border stripe style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column v-for="item in tableTile" :prop="item.key" :label="item.name"></el-table-column>
        <el-table-column label="使用组件">
          <template scope="scope" class="mytags">
            <el-tag v-if="scope.row.tenant_plugins" type="primary"
                    v-for="item in (scope.row.tenant_plugins||'').split(',')" style="margin-right: 5px;">
              {{item}}






            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页-->
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParm.currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageParm.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageParm.count" style="float:right">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny" @close="resetForm">
      <div class="form-warn">
        <el-form :model="form" :rules="editFormRules" ref="form" :label-width="formLabelWidth">
          <el-form-item label="租户名称" prop="tenant_name">
            <el-input v-model="form.tenant_name"
                      auto-complete="off"
                      show-message="!isUpdate"
                      :disabled="isUpdate"></el-input>
          </el-form-item>
          <el-form-item label="数据中心" prop="data_center_id">
            <el-select v-model="form.data_center_id"
                       placeholder="请选择数据中心"
                       show-message="!isUpdate"
                       :disabled="isUpdate">
              <el-option
                v-for="item in getDataCenterList"
                :label="item.data_center_name"
                :value="item.data_center_id">
              </el-option>
            </el-select>
            <!--<el-input v-model="getDataCenter.data_center_name"-->
            <!--:disabled="true">-->
            </el-input>
          </el-form-item>
          <el-form-item label="使用组件" prop="tenant_plugins">
            <el-select v-model="form.tenant_plugins"
                       @change="selCG"
                       size="large"
                       multiple placeholder="请选择">
              <el-option
                v-for="item in form.plugins"
                :label="item.assembly"
                :value="item.assembly">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="添加描述" prop="tenant_desc">
            <el-input v-model="form.tenant_desc"
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 8 }"
                      placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
  import util from '../../common/util'
  import dao from '../../common/dao'
  import Search from '../../components/Search.vue'
  import NProgress from 'nprogress'
  import UploadPath from '../../components/UploadPath'
  import { mapGetters } from 'vuex'

  export default {
    components: {Search, UploadPath},
    computed: {
      ...mapGetters([
        'getDataCenter',
        'getDataCenterList',
      ])
    },
    data() {
      return {
        dialogFormVisible: false,
        btnEditText: '提 交',
        formTitle: '创建租户',
        editLoading: false,
        form: {
          tenant_id: '',
          tenant_name: '',
          dataName: [],
          plugins: [],
          tenant_desc: '',
          data_center_id: '',
          tenant_plugins: []
        },
        formLabelWidth: '100px',
        editFormRules: {
          tenant_name: [
            {required: true, message: '请输入租户名称！', trigger: 'blur'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符！', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'},
            {validator: this.validatorName, trigger: 'blur'}
          ],
          data_center_id: [
            {type:'number', required: true, message: '请选择数据中心', trigger: 'change'},
            /*{
             required: true,
             validator: (reule, value, callback) => {
             if (isUpdate) {return false}
             callback()
             }, trigger: 'change'
             },*/
          ],
          tenant_desc: [{
            validator: (rule, value, callback, source, options) => {
              let strlength = value.replace(/[\u4E00-\u9FA5\uF900-\uFA2D]/, '**').length;
              if (strlength > 257) callback(new Error('描述长度不能超过 256 个字符!'));
              else callback()
            }, trigger: 'blur'
          }]
        },
        butStatus: {
          modify: true,
          deploy: true,
          add: false,
          rm: true
        },
        multipleSelection: [],
        formInline: {
          allOpts: [{
            key: 'tenant_name',
            label: '租户名称',
            type: '',
            val: ''
          }],
          cOpts: [{
            key: 'tenant_name',
            label: '租户名称',
            type: '',
            val: ''
          }]
        },
        tableTile: [{
          key: 'tenant_name',
          name: '租户名称'
        }, {
          key: 'data_center_name',
          name: '数据中心'
        }, {
          key: 'tenant_desc',
          name: '租户描述'
        }],
        tableData: [],
        pageParm: {
          "count": 0, //总条数
          "page_size": 20, //每页条数
          "page_count": 0, //总页数
          "currentPage": 1 //当前页数
        },
        tipsClass: "redTips",
        isUpdate: true
      }
    },
    methods: {
      selCG(val){
        if (val.indexOf('Hive') > -1 && val.indexOf('Hdfs') == -1) {
          this.form.tenant_plugins.push("Hdfs")
        }
        if (val.indexOf('phoenix') > -1 && val.indexOf('Hbase') == -1) {
          this.form.tenant_plugins.push("Hbase")
        }
      },
      getTenantInfoListHttp () { //获取列表
        let e = {
          "tenant_name": this.formInline.cOpts[0].val,
          "start_index": this.pageParm.currentPage,
          "page_count": this.pageParm.page_size
        };
        dao.getTenantInfoList(e).then((response) => {
          // success callback
          if (!response.body || response.body.retCode != 200) {
            util.apiMsg(response);
            return false;
          }
          let pageRes = response.body;
          this.tableData = pageRes.tenant_info_list;
          this.pageParm.count = parseInt(pageRes.count);
        }, (response) => {
          // error callback
          console.log(response)
        })
      },
      getDataCenterListHttp () { //获取数据中心
        dao.getDataCenterList({}).then((response) => {
          // success callback
          if (!response.body || response.body.retCode != 200) {
            util.apiMsg(response);
            return false
          }
          ;
          this.form.dataName = response.body.datacenter_info_list || [];
        })
      },
      getAssemblysHttp: function () { //获取组件
        dao.getAssemblys({"tenant_name": "tenant_name1"}).then((response) => {
          // success callback
          if (!response.body || response.body.retCode != 200) {
            util.apiMsg(response);
            return false
          }
          ;
          this.form.plugins = response.body.assemblys;
        })
      },
      validatorName (rule, value, callback) {

        if (!value) {
          callback(new Error('请输入租户名！'));
        } else {
          dao.getValidateTenant({
            "tenant_name": this.form.tenant_name,
            "tenant_id": this.form.tenant_id
          }).then((response) => {
            if (response.body.result) {
              callback(new Error('租户名重复！'));
            }
            callback();
          })
        }
      },
      gotopage42: function () { //获取选中的租户信息
        let tenantArray = [];
        let pluginsStr = "";
        let pluginsArray = [];
        this.tableData.map(item => {
          this.multipleSelection.map(obj => {
            if (item.tenant_id === obj.tenant_id) {
              let tenant_plugins = item.tenant_plugins;
              let tenantObj = {
                tenant_id: item.tenant_id,
                tenant_name: item.tenant_name,
                tenant_plugins: tenant_plugins
              }
              tenantArray.push(tenantObj);
            }
          });
        });
        if (tenantArray.length === 0) {
          this.$message({
            message: '请至少选择一条记录！',
            type: 'warning'
          });
        } else {
          util.save('page42_tenantArray', tenantArray);
          util.save('page42_butShow', true);
          this.$router.push({
            path: `/page42`,
          });
        }
      },
      editSubmit () {


        let param = {
          tenant_id: this.form.tenant_id,
          tenant_name: this.form.tenant_name,
          tenant_desc: this.form.tenant_desc,
          //data_center_id: this.getDataCenter.data_center_id,
          data_center_id: this.form.data_center_id,
          tenant_plugins: this.form.tenant_plugins.join(",")
        }
        if (this.isUpdate) { //修改
          this.$confirm('确认提交吗？', '提示', {
            type: 'info'
          }).then(() => {
            this.btnEditText = '提交中';
            this.editLoading = true;
            dao.getUpdateTenantInfo(param).then((response) => {
              this.btnEditText = '提 交';
              this.editLoading = false;
              this.dialogFormVisible = false;
              if (!response.body || response.body.retCode != 200) { return false; }
              else {
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });
                this.getTenantInfoListHttp();
              }
            });
          })

        } else { //创建

          this.$refs.form.validate((valid) => {
            if (!valid) {return false}
            this.$confirm('确认提交吗？', '提示', {
              type: 'info'
            }).then(() => {
              this.btnEditText = '提交中';
              this.editLoading = true;
              //create
              dao.getAddTenantInfo(param).then((response) => {
                this.btnEditText = '提 交';
                this.editLoading = false;
                this.dialogFormVisible = false;
                if (!response.body || response.body.retCode != 200) {
                  util.apiMsg(response);
                  return false;
                } else {
                  this.$message({
                    type: 'success',
                    message: '提交成功!'
                  });
                  //刷新列表
                  this.getTenantInfoListHttp();
                }
              });
            })
          })
        }
      },
      //创建
      createTenant: function () {

        this.dialogFormVisible = true
        this.form.tenant_id = "";
        this.form.tenant_name = "";
        this.form.tenant_desc = "";
        this.form.data_center_id = "";
        this.form.tenant_plugins = [];
        this.formTitle = "创建租户";
        this.form.zhHelpTips = "";
        this.isUpdate = false;

      },
      //更新
      updateTenant () {

        this.dialogFormVisible = true;
        this.isUpdate = true;
        //查询选中的租户信息
        let tenant_id = this.multipleSelection[0].tenant_id;
        this.tableData.map(item => {
          if (item.tenant_id === tenant_id) {
            this.form.tenant_id = item.tenant_id;
            this.form.tenant_name = item.tenant_name;
            this.form.tenant_desc = item.tenant_desc;
            this.form.data_center_id = item.data_center_id;
            let tenant_plugins = item.tenant_plugins;
            if (tenant_plugins != null) {
              let pluginsArray = tenant_plugins.split(",");
              this.form.tenant_plugins = pluginsArray;
            } else {
              this.form.tenant_plugins = [];
            }
          }

        });
        this.formTitle = "修改租户";
        this.form.zhHelpTips = "";
      },
      deleteTenant () { //删除
        //查询选中的租户id
        let tenant_id_list = []
        let deleteStatus = []
        let canDelete = 1
        this.multipleSelection.map(item => {
          tenant_id_list.push(item.tenant_id + "");
          deleteStatus.push(item.delete_status + "");
        })

        deleteStatus.map(ds => {
          let ms = ''
          if (ds == 1) {
            ms = '请先删除需要租户下面的策略'
          } else if (ds == 2) {
            ms = '请先解除角色绑定'
          } else if (ds == 3) {
            ms = '请先删除需要租户下面的策略和解除角色绑定'
          }
          if (ms) {
            this.$message({
              message: ms,
              type: 'warning'
            })
            canDelete = 0
            return false
          }
        })

        if (canDelete) {
          this.$confirm('确认删除吗？', '提示', {
            type: 'info'
          }).then(() => {
            dao.getDeleteTenantBatch({"tenant_id_list": tenant_id_list}).then((response) => {
              if (!response.body || response.body.retCode != 200) {
                util.apiMsg(response);
                return false;
              } else {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                //刷新列表
                this.getTenantInfoListHttp();
              }
            }, (response) => {
              console.log(response)
            });
          });
        }
      },
      updateButStatus: function (val) {

        if (val.length == 1) {
          this.butStatus.modify = false;
          this.butStatus.deploy = false;
          this.butStatus.rm = false;
        } else if (val.length == 0) {
          this.butStatus.modify = true;
          this.butStatus.deploy = true;
          this.butStatus.rm = true;
        } else {
          this.butStatus.modify = true;
          this.butStatus.deploy = false;
          this.butStatus.rm = false;
        }

      },
      handleSelectionChange: function (val) {
        this.multipleSelection = val
        this.updateButStatus(val)
      },
      handleSizeChange: function (val) {
        this.pageParm.page_size = val;
        this.getTenantInfoListHttp();
      },
      handleCurrentChange: function (val) {
        this.pageParm.currentPage = val;
        this.getTenantInfoListHttp();
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      }
    },
    mounted: function () {
      //this.getTableData();
      this.getTenantInfoListHttp();
      this.getDataCenterListHttp();
      this.getAssemblysHttp();
    }
  }
</script>

<style scoped>
  .toolbar {
    background: #fff;
    padding: 10px 10px 0px 10px;
  }

  .el-dialog .el-select {
    width: 100%;
  }

</style>